#!/usr/bin/env python3
# -*- conding: utf-8 -*-

import os,time,re
from datetime import datetime

st = time.time()

#根据开始数字重命名,前缀重名
#inpNum = input("请输入开始的下标(必须为数字,第一张图片名为输入的下标+1):")
inpNum = 0 #int(inpNum)
START_IDX = inpNum
NAME_LEN = 5
n = 1 #input("请输入图片名的前缀序号:")
NAME_STR = "img_piece_{0}_".format(n)
if NAME_STR=="":	
	for i in range(NAME_LEN):
		NAME_STR+='0'
	

#开始命名的数字:文件夹下的第一张图片名= START_IDX+1;当长度不足 NAME_LEN 前面补0

ROOT_PATH = os.path.abspath('..')
TEMP_STR = "__temp__"

if len(str(START_IDX))>NAME_LEN:
	print("命名长度小于开始下标的长度,请重新设置!!")
	exit()
	
#获取一个目录下面的所有png和jpg图片
def getDirImgs(curPath):
	allImgs=[x for x in os.listdir(curPath) if os.path.isfile(os.path.join(curPath,x)) and (os.path.splitext(os.path.join(curPath,x))[1]=='.png' or os.path.splitext(os.path.join(curPath,x))[1]=='.jpg') ]
	return allImgs

def getDirFolders(curPath):
	folders=[x for x in os.listdir(curPath) if os.path.isdir(os.path.join(curPath,x)) and x!="script"]
	return folders

def getNameByIdx(idx):
	ts = NAME_STR
	tlen=  NAME_LEN-len(str(idx))
	ts = NAME_STR + str(idx)
	return ts

def log(logs):	
	logurl = os.path.abspath("")#os.path.join(ROOT_PATH,'script')
	dts = str(datetime.now()).split('.')[0]
	dts = dts.replace(":","-")
	#dts = "".join(re.split(r'[\s]+',dts))
	dts = 'imgs'
	logurl = os.path.join(logurl,'logs_'+dts+'.txt')	
	with open(logurl,'w') as f:
		f.write(logs)
	print("日志文件已经保存在:{0} \n".format(logurl))
	
def renameImgs(imgs,folderName):
	logs = ""
	tidx = START_IDX
	print(" renameImgs folderName:",folderName)
	reobj = re.search(r'\d+',folderName)
	#print("reobj",reobj.group())
	name_fix = "img_piece_{0}_".format(reobj.group())
	for fname in imgs:
		oname = os.path.join(ROOT_PATH,folderName,fname)
		tidx+=1
		newName = name_fix+str(tidx)+os.path.splitext(oname)[1] #getNameByIdx(tidx)
		newName = os.path.join(ROOT_PATH,folderName,newName)
		logOldName = oname.replace(TEMP_STR,'')
		log = '把图片:{0}；重命名为：{1};\r\n'.format(logOldName,newName)
		logs+=log
		print(log)		
		os.rename(oname,newName)		
	return logs,(tidx-START_IDX)

def renameTemp(imgs):
	for fname in imgs:
		oname = os.path.join(ROOT_PATH,fname)
		olds = os.path.splitext(oname)
		newName = olds[0]+TEMP_STR+olds[1]
		os.rename(oname,newName)
	
print("\n开始重命名 {0} 目录下的图片文件\n".format(ROOT_PATH))
folders = getDirFolders(ROOT_PATH)

'''
print("folders:",folders)
folder = "神器24_T天官笔"
reobj = re.search(r'\d+',folder)
print("reobj",reobj.group())
exit();
'''
total = 0
for folder in folders:
	print("folder",folder)
	path = os.path.join(ROOT_PATH,folder)
	#imgs = getDirImgs(path)
	#renameTemp(imgs)
	print("path",path)
	imgs = getDirImgs(path)
	imgs.sort()
	logs,num = renameImgs(imgs,folder)
	log(logs)
	total = total+num


et = time.time()

print("重命名完成,总耗时 {0} 毫秒，共重命名操作了 {1} 个文件\n".format(round(et-st,2),total))
	

